﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Unicode;

namespace DFGK_WMS.WebAPI.Controllers.库存管理
{
    /// <summary>
    /// 库存汇总
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TInventorySummaryController : ControllerBase
    {
        private readonly ITInventorySummaryRepository TInventorySummary;

        public TInventorySummaryController(ITInventorySummaryRepository TInventorySummary)
        {
            this.TInventorySummary = TInventorySummary;
        }

        /// <summary>
        /// 关键字查询
        /// </summary>
        /// <param name="keywords"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInventorySummary(string ? keywords, int pageIndex, int pageSize)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            var list = TInventorySummary.GetInventorySummary(out var totalCount, keywords, pageIndex, pageSize);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));

            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }


        /// <summary>
        /// 库存汇总导出方法
        /// </summary>
        /// <returns></returns>
        MemoryStream ProcessExcelData()
        {
            //模块从表中读取的数据
            List<TInventory> list = new List<TInventory>();
            list = TInventorySummary.GetSummaryExcel();
            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("库存汇总");  // 创建Excel中的表对象
                                                           //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("序号"); // 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("物料名称");
            row0.CreateCell(2).SetCellValue("物料号");
            row0.CreateCell(3).SetCellValue("货主");
            row0.CreateCell(4).SetCellValue("数量");
            row0.CreateCell(5).SetCellValue("总计");
            var rowIndex = 1;
            foreach (var item in list)
            {
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.Id);
                row.CreateCell(1).SetCellValue(item.MaterialName);
                row.CreateCell(2).SetCellValue(item.MaterialCode);
                row.CreateCell(3).SetCellValue(item.OwnerName);
                row.CreateCell(4).SetCellValue(item.AvailableQty.ToString());
                row.CreateCell(5).SetCellValue(item.TotalPrice.ToString());

                rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }

        /// <summary>
        /// 库存汇总导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult GetSummaryExcel()
        {
            MemoryStream ms = ProcessExcelData();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var encoding = Encoding.GetEncoding("UTF-8");
            
            byte[] fileBytes = ms.ToArray();

            string encodedFileName = System.Net.WebUtility.UrlEncode("库存汇总.xlsx");

            Response.Headers.Add("Content-Disposition", $"attachment; filename={encodedFileName}");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8";


            // 返回文件内容
            return File(fileBytes, Response.ContentType);
        }

        /// <summary>
        /// 获取物料分类
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialClassification()
        {

            var list = TInventorySummary.GetMaterialClassification();
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));

            }
            return Ok(BaseResult.Result(null, "查询失败！", "500"));
        }

        /// <summary>
        /// 根据ID查询物料信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialInformationById(int id)
        {
            if(id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var list = TInventorySummary.GetMaterialInformationById(id);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));

            }
            return Ok(BaseResult.Result(null, "查询失败！", "500"));
        }

    }
}
